#-*- coding:utf-8 -*-
import os
import sys
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
from Widgets.status_comboBox import StatusComb
# from Widgets.palette_color import showColor

class MainTableWidget(QTableWidget):
    shot_name_Signal=Signal(tuple) #(self.current_real_shot_path,shot_name)
    count_price_Signal=Signal(tuple)#将当前显示数量与总价发给总窗口
    def __init__(self):
        super(MainTableWidget,self).__init__()
        # self.setPalette(showColor('bg'))

        self.setStyleSheet('::section{background-color:rgb(75,75,75);color:rgb(200,200,200)}QTableWidget{background-color:rgb(75,75,75);color:rgb(200,200,200)}'
                           'QScrollBar{background-color:rgb(100,100,100);width:10px}QHeaderView{background-color:rgb(75,75,75);color:rgb(200,200,200)}')

        self.row_count=20 #记得再传数据的时候一定要重设掉
        self.column_count=6

        self.setRowCount(self.row_count)
        self.setColumnCount(self.column_count)

        self.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.horizontalHeader().setDefaultSectionSize(150)

        #全局变量
        self.current_real_epi_path=''
        self.current_real_shot_path=''#当前镜头路径

        self.H_list=['制作者','分配时长(/天)','审核状态','制作价格(/元)','制作内容','开始时间'] #水平表头
        self.V_list=['              ','              ']

        self.setHorizontalHeaderLabels(self.H_list)
        self.setVerticalHeaderLabels(self.V_list)

        self.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)
        self.verticalHeader().setDefaultSectionSize(50)
        self.verticalHeader().setDefaultAlignment(Qt.AlignCenter)
        #绑定内容单击事件
        self.clicked.connect(self.__onclick)

        #绑定标题单击事件
        self.verticalHeader().sectionClicked.connect(self.__shot_click)


        # 添加右击菜单  思考再三，右击先取消掉，毕竟现在还没有太多要求
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.__rightMenu)

        #
        self.cellChanged.connect(self.__cell_changed)
        # self.cellActivated()
        # self.cellClicked()
        # self.cellDoubleClicked()
        # self.cellEntered.connect(self.__cell_changed)
        # self.cellPressed.connect(self.__cell_changed)

        #test
        # self.__getInfoByRow_withoutStatus(2)


    def __rightMenu(self,pos):
        allIndexs=self.selectionModel().selection().indexes()
        menu=QMenu()
        c=-1
        for i in allIndexs:
            c=i.column()

        if c==0:
            nameFilterAction=QAction('仅查看此人',self)
            nameFilterAction.triggered.connect(self.__nameFilter)
            menu.addAction(nameFilterAction)


        elif c==1:
            givenTimeFilterAction=QAction('仅查看此分配时长',self)
            givenTimeFilterAction.triggered.connect(self.__givenTimeFilter)
            menu.addAction(givenTimeFilterAction)

        elif c==2:
            statusFilterAction=QAction('仅查看此类状态',self)
            statusFilterAction.triggered.connect(self.__statusFilter)
            menu.addAction(statusFilterAction)

        elif c==3:
            priceFilterAction=QAction('仅查看此价格',self)
            priceFilterAction.triggered.connect(self.__priceFilter)
            menu.addAction(priceFilterAction)
        elif c==4:
            contentFilterAction=QAction('仅查看此内容',self)
            contentFilterAction.triggered.connect(self.__contentFilter)
            menu.addAction(contentFilterAction)
        elif c==5:
            startDayFilterAction=QAction('仅查看此起始日期',self)
            startDayFilterAction.triggered.connect(self.__startDayFilter)
            menu.addAction(startDayFilterAction)
        else:
            pass


        # if c==0:
        #     renameAction=QAction('修改姓名',self)
        #     menu.addAction(renameAction)
        #
        # elif c==1:
        #     retimeAction=QAction('修改时间',self)
        #     menu.addAction(retimeAction)
        #
        # elif c==2:
        #     pass
        # else:
        #     priceAction=QAction('修改价格',self)
        #     menu.addAction(priceAction)

        menu.exec_(QCursor.pos())

    #过滤
    def __nameFilter(self):
        # indexs=self.selectedIndexes()
        # pos=indexs[0].column()
        # print(pos)
        namelist=[]

        items=self.selectedItems()
        for i in items:
            if i:
                name=i.text()
                if name not in namelist:
                    namelist.append(name)
        # print(namelist)
        self.__filter(0,namelist)

        temp_tuple = self.count_total_price_Info()
        self.count_price_Signal.emit(temp_tuple)

    def __givenTimeFilter(self):

        timelist=[]

        items=self.selectedItems()
        for i in items:
            if i:
                name=i.text()
                if name not in timelist:
                    timelist.append(name)

        self.__filter(1,timelist)

        temp_tuple = self.count_total_price_Info()
        self.count_price_Signal.emit(temp_tuple)

    def __statusFilter(self):

        statuslist=[]

        indexs=self.selectedIndexes()
        for i in indexs:
            r=i.row()
            comb_widget = self.cellWidget(r, 2)  # 前面定死了第3列就是状态栏
            comb_index = comb_widget.comb.currentIndex()  # 获取当前comb索引值
            if comb_index not in statuslist:
                statuslist.append(comb_index)


        self.__combFilter(2,statuslist)

        temp_tuple = self.count_total_price_Info()
        self.count_price_Signal.emit(temp_tuple)


    def __priceFilter(self):
        pricelist=[]

        items=self.selectedItems()
        for i in items:
            if i:
                name=i.text()
                if name not in pricelist:
                    pricelist.append(name)

        self.__filter(3,pricelist)

        temp_tuple = self.count_total_price_Info()
        self.count_price_Signal.emit(temp_tuple)


    def __contentFilter(self):
        contentlist=[]

        items=self.selectedItems()
        for i in items:
            if i:
                name=i.text()
                if name not in contentlist:
                    contentlist.append(name)

        self.__filter(4,contentlist)

        temp_tuple = self.count_total_price_Info()
        self.count_price_Signal.emit(temp_tuple)

    def __startDayFilter(self):
        startDaylist=[]

        items=self.selectedItems()
        for i in items:
            if i:
                name=i.text()
                if name not in startDaylist:
                    startDaylist.append(name)

        self.__filter(5,startDaylist)

        temp_tuple = self.count_total_price_Info()
        self.count_price_Signal.emit(temp_tuple)



    def __filter(self,c,text_list):
        # self.setFocusPolicy(Qt.NoFocus)

        for i in range(5):
            r_list = []
            for r in range(self.rowCount()):
                if self.item(r,c):
                    current_text=self.item(r,c).text()
                    # print(current_text)
                    if current_text not in text_list:
                        r_list.append(r)

            r_list.sort(reverse=True)
            for i in r_list:
                self.removeRow(i)

    def __combFilter(self,c,status_list):

        for i in range(5):
            r_list=[]
            for r in range(self.rowCount()):
                comb_widget = self.cellWidget(r, 2)  # 前面定死了第3列就是状态栏
                comb_index = comb_widget.comb.currentIndex()  # 获取当前comb索引值
                if comb_index not in status_list:
                    r_list.append(r)

            r_list.sort(reverse=True)
            for i in r_list:
                self.removeRow(i)

    def show_all_info(self,tuple):
        '''
        该函数显示所有的镜头info,以tuple的形式传进来
        :param tuple: 集数那边传的所有信息为：当前集数路径，所有镜头名称，所有镜头名称对应的info信息
        (self.current_real_epi_path,
        [shot_name1,shot_name2],
        [{shot_name1:{artist:xxx,given_time:xxx,status:xxx,price:xxx,requirement:xxx,start_day:xxx}},
        {shot_name2:{artist:xxx,given_time:xxx,status:xxx,price:xxx,requirement:xxx,start_day:xxx}}])
        :return:
        '''
        self.current_real_epi_path=tuple[0]
        shot_name_list=tuple[1]
        shot_info_list=tuple[2]
        for i in range(len(tuple[1])):#循环名称列表就是表格的水平坐标row
            shot_name=shot_name_list[i]
            info=shot_info_list[i][shot_name]
            self.__showOneShot(i,info)






    def __showOneShot(self,r,info):
        '''
        传入行数，与当前镜头信息
        集数那边传的所有信息为：当前集数路径，所有镜头名称，所有镜头名称对应的info信息
        (self.current_real_epi_path,
        [shot_name1,shot_name2],
        [{shot_name1:{artist:xxx,given_time:xxx,status:xxx,price:xxx,requirement:xxx,start_day:xxx}},
        {shot_name2:{artist:xxx,given_time:xxx,status:xxx,price:xxx,requirement:xxx,start_day:xxx}}])

        :param r: 行数
        :param info: 镜头的info信息
        :return:
        '''
        textPos=[(r,0),(r,1),(r,3),(r,4),(r,5)] #文本显示坐标
        combPos=(r,2)#comboBox坐标
        text_list=[info['artist'],str(info['given_time']),str(info['price']),info['requirement'],info['start_day']]
        for i in range(len(textPos)):
            self.setItemText(textPos[i],text_list[i])

        comb=StatusComb(combPos,info['status'])
        # comb.setStatus(info['status'])#不要这个来初始化，会被实时监听到
        comb.status_Signal.connect(self.__getCombSignal)
        self.setCellWidget(combPos[0],combPos[1],comb)

    def setItemText(self,pos,text):
        item=QTableWidgetItem()
        item.setText(text)
        item.setTextAlignment(Qt.AlignCenter)
        self.setItem(pos[0],pos[1],item)


    def __getCombSignal(self,i):
        '''
        槽函数，实时更新当前镜头的info的status
        :param i:从comboBox传来的当前comb的坐标以及更新值
        :return:
        '''
        # print(i)
        r=i[0][0]#int(i[0][0])
        status=i[1]
        print(i)
        shot_name=self.verticalHeaderItem(r).text()
        current_real_shot_dir_path=os.path.join(self.current_real_epi_path,shot_name)
        current_real_info_path=os.path.join(current_real_shot_dir_path,'info')


        info_list_without_status=self.__getInfoByRow_withoutStatus(r)
        new_info_dic={}
        new_info_dic['artist']=info_list_without_status[0]
        new_info_dic['given_time'] = info_list_without_status[1]
        new_info_dic['status'] = status
        new_info_dic['price'] = info_list_without_status[2]
        new_info_dic['requirement'] = info_list_without_status[3]
        new_info_dic['start_day'] = info_list_without_status[4]


        with open(current_real_info_path,'w',encoding='utf-8') as w:
            w.write(str(new_info_dic))


    def __getInfoByRow_withoutStatus(self,r):
        '''
        内置计算函数，用来计算给定行数r，返回当前r行的所有状态信息
        :param r:
        :return:制作者,分配时长,制作价格,制作内容，开始时间
        '''
        text_List=[self.item(r,0).text(),self.item(r,1).text(),self.item(r,3).text(),self.item(r,4).text(),self.item(r,5).text()]

        return text_List




    def __cell_changed(self,r,c):
        '''
        实时监听函数，在第一次刷新全页面的时候，一定会报错，因为在写与设置菜单。可能为空。
        所有用try来强行忽略起始刷新错误
        :param r:
        :param c:
        :return:
        '''
        if c!=2:#为防止意外，先不考虑状态栏
            try:
                shot_name = self.verticalHeaderItem(r).text()
                current_real_shot_dir_path = os.path.join(self.current_real_epi_path, shot_name)
                current_real_shot_path = os.path.join(current_real_shot_dir_path, 'info')

                info_list_without_status = self.__getInfoByRow_withoutStatus(r)

                comb_widget=self.cellWidget(r,2)#前面定死了第3列就是状态栏
                comb_index=comb_widget.comb.currentIndex() #获取当前comb索引值

                new_info_dic = {}
                new_info_dic['artist'] = info_list_without_status[0]
                new_info_dic['given_time'] = info_list_without_status[1]
                new_info_dic['status'] = comb_index
                new_info_dic['price'] = info_list_without_status[2]
                new_info_dic['requirement'] = info_list_without_status[3]
                new_info_dic['start_day'] = info_list_without_status[4]

                with open(current_real_shot_path, 'w', encoding='utf-8') as w:
                    w.write(str(new_info_dic))
            except:
                # QMessageBox.information(self,'错误','读写错误')
                pass


    def __shot_click(self,index):
        '''
        表头槽函数，返回当前点击的表头索引,注意这里的index不是r,c坐标
        :param index: eg :0 ,1 ,2 ,3
        :return:
        '''
        try:
            shot_name=self.verticalHeaderItem(index).text()
            self.current_real_shot_path=os.path.join(self.current_real_epi_path,shot_name)
            start_day = self.item(index,5).text()
            given_time=self.item(index,1).text()
            temp_tuple=(self.current_real_shot_path,shot_name,start_day,given_time)

            self.shot_name_Signal.emit(temp_tuple)
        except:
            print('内容为空')

    def updateRowCount(self,r):
        self.setRowCount(r)

    def updateColumnCount(self,c):
        self.setColumnCount(c)


    def setH_list(self,custom_list):
        '''
        设置水平表头显示
        :param custom_list:
        :return:
        '''
        self.setHorizontalHeaderLabels(custom_list)
        self.H_list=custom_list #更新全局记录的当前水平表头内容

    def setV_list(self,custom_list):
        '''
        设置垂直表头内容
        :param custom_list:
        :return:
        '''
        self.setVerticalHeaderLabels(custom_list)
        self.V_list=custom_list


    def __onclick(self):
        '''
        单击事件主要是将当前操作的镜头路径、镜头名称发给主界面，好实现删除、读取任务信息等功能
        注意，状态栏一直是None
        :return:
        '''
        # item=QTableWidgetItem()
        # item.row()
        currentItem=self.currentItem()


        if currentItem:
            index=currentItem.row()
            shot_name=self.verticalHeaderItem(index).text()
            if shot_name:
                self.current_real_shot_path = os.path.join(self.current_real_epi_path, shot_name)
                start_day = self.item(index, 5).text()
                given_time = self.item(index, 1).text()
                temp_tuple = (self.current_real_shot_path, shot_name,start_day,given_time)
                self.shot_name_Signal.emit(temp_tuple)
            else:
                pass

    def set_item(self,r,c,content):
        '''
        设置指定坐标的内容，这个针对单个框修改
        :param r:
        :param c:
        :param content:
        :return:
        '''
        if c!=2:#当不是状态栏时
            item=QTableWidgetItem()
            item.setTextAlignment(Qt.AlignCenter)
            item.setText(content)
            self.setItem(r,c,item)

        else:#当是状态栏时
            status=['制作中','通过','返修','暂停']
            style=['QComboBox{color:#FFA500}','QComboBox{color:#90EE90}','QComboBox{color:#FF0000}','QComboBox{color:#696969}']
            comb=QComboBox()
            comb.addItems(status)
            comb.setFont(QFont('',12,75))
            comb.setStyleSheet(style[content])
            comb.setCurrentIndex(content)







    def __addBtn(self):
        '''
        右击添加新镜头
        :return:
        '''
        pass




    def verticalClear(self):
        self.clear()
        self.setHorizontalHeaderLabels(self.H_list)


    def count_total_price_Info(self):
        '''
        该函数是用来计算当前列表中的总列数量，以及所有价格的总价
        :return:
        '''

        count=self.rowCount()
        total_price=0
        for i in range(count):
            price=self.item(i,3).text()
            total_price+=float(price)

        return (count,total_price)


if __name__ == '__main__':
    app=QApplication(sys.argv)
    maintable=MainTableWidget()
    maintable.show()
    sys.exit(app.exec_())